/*
 * @Author: Yuluo 568055454@qq.com
 * @Date: 2023年06月23日 13:59:48
 * @LastEditors: Yuluo 568055454@qq.com
 * @LastEditTime: 2023年07月15日 22:15:45
 * @FilePath: \Mood-Blog-System\blog\src\utils\storage\localStorage.ts
 * @Description: 本地存储localStorage
 * Copyright (c) 2023 by Yuluo, All Rights Reserved. 
 */
interface StorageOptions {
    prefix?: string;
}
/**
 * @description: 设置localStorage
 * @param {string} key 键
 * @param {any} value 值
 * @param {StorageOptions} options 配置项
 * @return {*}  void
 */
export function setLocalStorageItem(key: string, value: any, options?: StorageOptions): void {
    try {
        const prefix = options?.prefix || '';
        const serializedValue = typeof value === 'string' ? value : JSON.stringify(value);
        localStorage.setItem(prefix + key, serializedValue);
    } catch (error) {
        console.error('Error while setting item in localStorage:', error);
    }
}

/**
 * @description: 获取localStorage
 * @param {string} key 键
 * @param {StorageOptions} options 配置项
 * @return {*} T | null
 */
export function getLocalStorageItem<T>(key: string, options?: StorageOptions): T | null {
    try {
        const prefix = options?.prefix || '';
        const serializedValue = localStorage.getItem(prefix + key);
        if (serializedValue) {
            try {
                return JSON.parse(serializedValue) as T;
            } catch (error) {
                return serializedValue as T;
            }
        }
    } catch (error) {
        console.error('Error while getting item from localStorage:', error);
    }
    return null;
}

/**
 * @description: 删除localStorage
 * @param {string} key 键
 * @param {StorageOptions} options 配置项
 * @return {*} void
 */
export function removeLocalStorageItem(key: string, options?: StorageOptions): void {
    try {
        const prefix = options?.prefix || '';
        localStorage.removeItem(prefix + key);
    } catch (error) {
        console.error('Error while removing item from localStorage:', error);
    }
}

/**
 * @description: 清空localStorage
 * @return {*}  void
 */
export function clearLocalStorage(): void {
    try {
        localStorage.clear();
    } catch (error) {
        console.error('Error while clearing localStorage:', error);
    }
}
